<?php

class IndexController extends Backend_Base_Controller
{

    public function init()
    {
        parent::init();
    }

    public function indexAction()
    {

    }

    public function loginAction()
    {

        $form    = new Application_Form_Auth_Mgmt();
        $request = $this->getRequest();

        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($request->getPost()))
            {
                $form_values  = $form->getValues();
                $mgmtLogin    = $form_values['login'];
                $mgmtPassword = $form_values['password'];

                if ($mgmtLogin && $mgmtPassword)
                {
                    $mapper = new Application_Model_AdminMapper();
                    $admin  = $mapper->findByLoginAndPassword($mgmtLogin, $mgmtPassword);
                    if (!empty($admin) && $admin->getId() > 0)
                    {
                        $mapper->updateLastAccess($admin->getId());
                        $general_settings = Zend_Registry::get('general');
                        if (!empty($general_settings['sessionNamespace']))
                        {
                            $mgmtNamespaceName = $general_settings['sessionNamespace'];
                            $mgmtNamespace     = new Zend_Session_Namespace($general_settings['sessionNamespace']);

                            $mgmtNamespace->id    = $admin->getId();
                            $mgmtNamespace->admin = $admin;

                            Zend_Registry::set('session', $mgmtNamespace);
                            $this->_helper->message($this->view->translate('You are successfully logged in!'), Backend_Flash_Messenger::TYPE_SUCCESS);
                            $this->_helper->redirector('index');
                        }
                    }
                }
            }
        }

        $this->view->form = $form;
        $this->_helper->_layout->setLayout('login');
    }

    public function logoutAction()
    {
        $general_settings = Zend_Registry::get('general');
        if (!empty($general_settings['sessionNamespace']))
        {
            $mgmtNamespaceName = $general_settings['sessionNamespace'];
            $mgmtNamespace     = new Zend_Session_Namespace($general_settings['sessionNamespace']);
            $mgmtNamespace->unsetAll();

            $this->_helper->redirector('index');
        }
    }
}

